#include <algorithm>
using namespace std;
#include <vector>
#include <queue>

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    explicit TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution
{
public:
    static vector<vector<int>> zigzagLevelOrder(TreeNode* root)
    {
        vector<vector<int>> rvv;
        if(root == nullptr)
            return rvv;
        queue<TreeNode*> q;
        q.push(root);
        int level = 1;

        while(!q.empty())
        {
            int sz = q.size();
            vector<int> tmp;
            while(sz--)
            {
                auto t = q.front();
                tmp.push_back(t->val);
                q.pop();
                if(t->left != nullptr)
                    q.push(t->left);
                if(t->right != nullptr)
                    q.push(t->right);
            }
            if(level%2 == 0)
                reverse(tmp.begin(), tmp.end());
            rvv.push_back(tmp);
            level++;
        }
        return rvv;
    }
};
